from datetime import datetime
import uuid
from models.database import get_db_connection

class History:
    def __init__(self, history_id=None, user_id=None, prompt_text=None, style=None, 
                 output_url=None, params=None, is_dynamic=False, animation_type=None, 
                 created_at=None, likes=0, downloads=0):
        self.history_id = history_id or str(uuid.uuid4())
        self.user_id = user_id
        self.prompt_text = prompt_text
        self.style = style
        self.output_url = output_url
        self.params = params
        self.is_dynamic = is_dynamic
        self.animation_type = animation_type
        self.created_at = created_at or datetime.now()
        self.likes = likes
        self.downloads = downloads

    @staticmethod
    def find_by_user_id(user_id):
        """获取用户的历史记录"""
        conn = get_db_connection()
        if not conn:
            return []
            
        cursor = conn.cursor(dictionary=True)
        cursor.execute(
            "SELECT * FROM history WHERE user_id = %s ORDER BY created_at DESC",
            (user_id,)
        )
        history_data = cursor.fetchall()
        cursor.close()
        conn.close()
        
        return history_data
    
    @staticmethod
    def find_by_id(history_id):
        """根据ID查找历史记录"""
        conn = get_db_connection()
        if not conn:
            return None
            
        cursor = conn.cursor(dictionary=True)
        cursor.execute("SELECT * FROM history WHERE history_id = %s", (history_id,))
        history_data = cursor.fetchone()
        cursor.close()
        conn.close()
        
        return history_data
    
    def save(self):
        """保存历史记录到数据库"""
        conn = get_db_connection()
        if not conn:
            return False
            
        cursor = conn.cursor()
        try:
            cursor.execute(
                "INSERT INTO history (history_id, user_id, prompt_text, style, output_url, "
                "is_dynamic, animation_type, created_at, likes, downloads) "
                "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
                (self.history_id, self.user_id, self.prompt_text, self.style, self.output_url,
                 self.is_dynamic, self.animation_type, self.created_at, self.likes, self.downloads)
            )
            conn.commit()
            cursor.close()
            conn.close()
            return True
        except Exception as e:
            print(f"保存历史记录时出错: {str(e)}")
            conn.rollback()
            cursor.close()
            conn.close()
            return False